package com.graduation.clientback.controller;

import com.graduation.clientback.common.R;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.util.UUID;

@RestController
@RequestMapping("/upload")
public class CommonController {

    @Value("${graduation.profile}")
    private String profile;

    private static final String ROOT_PATH = "D:\\ruoyi\\uploadPath\\upload\\"; // 根目录

    @PostMapping("/img")
    public R<String> upload(MultipartFile file) throws IOException {
        try {
            // 获取当前日期
            LocalDate now = LocalDate.now();
            // 按照年/月/日格式化日期
            String datePath = now.getYear() + "\\" + now.getMonthValue() + "\\" + now.getDayOfMonth();
            // 完整的文件存储路径
            Path fullPath = Paths.get(ROOT_PATH, datePath);
            // 如果路径不存在，则创建该路径
            if (!Files.exists(fullPath)) {
                Files.createDirectories(fullPath);
            }
            // 生成唯一的文件名来避免覆盖已有的文件
            String fileName = UUID.randomUUID().toString() + "_" + file.getOriginalFilename();
            // 文件存储路径
            Path filePath = fullPath.resolve(fileName);
            // 将文件写入指定的位置
            Files.write(filePath, file.getBytes());
            // 构建文件的URL
            String fileDownloadUrl = "/profile/upload/" + datePath.replace("\\", "/") + "/" + fileName;
            return R.success(fileDownloadUrl);
        } catch (IOException e) {
            e.printStackTrace();
            return R.error("上传文件失败");
        }
    }
}
